/**
 * Copyright (c) 2010
 * Bert Young. UESTC. 
 */

#ifndef BERT_TCPCLIENTTHREAD_H
#define BERT_TCPCLIENTTHREAD_H

#include <string>
#include "SocketConnection.h"
#include "Thread.h"
#include "MsgBuffer.h"

#include "debug.h"

class TCPClientThread : public Thread
{
protected:
	/**
	 * The client socket connection
	 */
	SocketConnection * pSocket;
	/**
	 * Buffered or nonbuffer
	 */
	volatile bool buffered;
public:
	/**
	 * Constructor
	 */
	TCPClientThread(const std::string & servip = "127.0.0.1",
			const unsigned short port = 8888
			)
		: pSocket(NULL), serverIP(servip), serverPort(port)
	{
		buffered = false;
	}
	/**
	 * Destructor
	 */
	virtual ~TCPClientThread()
	{
		finalSync();
		delete pSocket;
		pSocket = NULL;
	}
	/**
	 * 服务器ip
	 */
	std::string serverIP;
	/**
	 * 服务器端口
	 */
	unsigned short serverPort;
	/**
	 * Create socket and connect to servip
	 */
	bool connect( const char * servip, const unsigned short port);
	/**
	 * msg parse or put msg to queue
	 */
	virtual void parse(const void *cmd, unsigned int len) = 0;
#if 0
	/**
	 * connect成功后，主动向服务器发指令，等待验证
	 */
	bool sendLoginCmd()
	{
		// todo...
		return true;
	}
#endif
	/**
	 * Send cmd
	 */
	bool sendPacket(const void *cmd, unsigned int len);
	/**
	 * Do the IO
	 */
	void run();
	/**
	 * 将缓冲的数据发走
	 */
	void finalSync();
	/**
	 * Send data
	 */
	bool send();
	/**
	 * Receive data
	 */
	bool recv();
	/**
	 * Receive data
	 */
	int recvPacket(void *cmd, bool wait = true)
	{
		return pSocket->recvPacket(cmd, wait);
	}
};

class TCPClientThreadNoBuffer : public TCPClientThread, public MsgParse
{
	/**
	 * 在本线程直接解析消息；也就是IO与逻辑耦合
	 */
	virtual void parse(const void * cmd, unsigned int len);
};

class TCPClientThreadBuffer : public TCPClientThread, public MsgBuffer
{
	/**
	 * 在逻辑线程解析消息；也就是IO与逻辑分离
	 */
	virtual void parse(const void * cmd, unsigned int len);
};

#endif

